﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using WCYCReader.Resources;
using System.Windows.Threading;
using WCYCReader.Models;
using System.Windows.Media;
using WCYCReader.Utility;
using WCYCReader.Main;
using System.ComponentModel;
using Microsoft.Phone.Info;
using WCYCReader.Main.Core;
using WCYCReader.UserControls;
using Microsoft.Phone.Tasks;
using System.Net.NetworkInformation;
using System.Windows.Media.Imaging;

namespace WCYCReader
{
    public partial class MainPage : PhoneApplicationPage
    {

        public HelpControl hc = new HelpControl();
        public DispatcherTimer downloadUpdateTime = new DispatcherTimer();
        public bool downloadUpdateTimeBegin;
        private BookList_M TodayRecommended_M = new BookList_M();
        private bool menuChanged;

        public MainPage()
        {
            this.InitializeComponent();
            if ((Visibility)Application.Current.Resources["PhoneDarkThemeVisibility"] != Visibility.Visible)
            {
                SolidColorBrush solidColorBrush = new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));
                Application.Current.Resources.Add("PhoneBackgroundBrush", solidColorBrush);
            }
            if (SettingHelper.IsSettings("BookReader_Default"))
            {
                App.ReaderPage_Night = (bool)SettingHelper.GetValueFromSettings("BookReader_NightMode");
            }
            else
            {
                SettingHelper.SaveInToSettings("BookReader_Default", true);
                SettingHelper.SaveInToSettings("BookReader_fontSize", 26);
                SettingHelper.SaveInToSettings("BookReader_BackgroundNum", 0);
                SettingHelper.SaveInToSettings("ReaderPage_Bright", 0.08);
                SettingHelper.SaveInToSettings("ReaderPage_NightBright", 0.5);
                SettingHelper.SaveInToSettings("BookReader_NightMode", false);
                App.ReaderPage_Night = false;
                InternalBook.AddInternalBook();
            }
            base.Loaded += this.MainPage_Loaded;
        }

        private void ApplicationBarIconButton_About(object sender, EventArgs e)
        {
            NaviService.Navigate(QQReaderPage.EAboutPage, "");
        }

        private void ApplicationBarIconButton_Feedback(object sender, EventArgs e)
        {
            NaviService.Navigate(QQReaderPage.EFeedbackPage, "");
        }

        private void bookListBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBox listBox = sender as ListBox;
            if (listBox.SelectedIndex >= 0 && 2 == App.LocalBook.T_LocalBookList_VM1()[listBox.SelectedIndex].int_IsDownload_M)
            {
                NaviService.Navigate(QQReaderPage.EBookReaderPage, string.Concat("?FileName=", App.LocalBook.T_LocalBookList_VM1()[listBox.SelectedIndex].str_Id_M));
                SaveReaderHistory.Delete(App.LocalBook.T_LocalBookList_VM1()[listBox.SelectedIndex]);
                SaveReaderHistory.Save(App.LocalBook.T_LocalBookList_VM1()[listBox.SelectedIndex]);
                SettingHelper.SaveInToSettings("ReaderPageBack", true);
            }
            listBox.SelectedIndex = -1;
        }

        private void bookListBox2_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBox listBox = sender as ListBox;
            if (listBox.SelectedIndex >= 0 && 2 == App.LocalBook.T_LocalBookList_VM2()[listBox.SelectedIndex].int_IsDownload_M)
            {
                NaviService.Navigate(QQReaderPage.EBookReaderPage, string.Concat("?FileName=", App.LocalBook.T_LocalBookList_VM2()[listBox.SelectedIndex].str_Id_M));
                SaveReaderHistory.Delete(App.LocalBook.T_LocalBookList_VM2()[listBox.SelectedIndex]);
                SaveReaderHistory.Save(App.LocalBook.T_LocalBookList_VM2()[listBox.SelectedIndex]);
                SettingHelper.SaveInToSettings("ReaderPageBack", true);
            }
            listBox.SelectedIndex = -1;
        }

        public void CheckUpdate()
        {
            Dictionary<string, string> strs = new Dictionary<string, string>();
            WebHeaderCollection webHeaderCollections = new WebHeaderCollection();
            if (SettingHelper.IsSettings("QQReader_sid"))
            {
                webHeaderCollections["sid"] = SettingHelper.GetValueFromSettings("QQReader_sid") as string;
            }
            webHeaderCollections["c_version"] = "qqreader_1.0.0_0001_wp7";
            webHeaderCollections["ua"] = DeviceExtendedProperties.GetValue("DeviceName").ToString();
            webHeaderCollections["c_platform"] = "wp7";
            HttpPostClient httpPostClient = new HttpPostClient(strs, webHeaderCollections);
            httpPostClient.DownloadStringAsync(new Uri("http://allreader.3g.qq.com/checkupdate", UriKind.Absolute));
            httpPostClient.DownloadStringCompleted += this.CheckUpdate_DownloadStringCompleted;
        }

        private void CheckUpdate_DownloadStringCompleted(object sender, WCYCReader.Main.Core.DownloadStringCompletedEventArgs e)
        {
            base.Dispatcher.BeginInvoke(() =>
            {
                if (e.Result == null)
                {
                    return;
                }
                UpdateJsonData updateJsonDatum = new UpdateJsonData();
                updateJsonDatum = ParseJson.Parse<UpdateJsonData>(e.Result);
                if (updateJsonDatum.update_code == "0")
                {
                    return;
                }
                if (updateJsonDatum.update_code == "2")
                {
                    if (MessageBoxResult.OK == MessageBox.Show("发现新版本，是否升级？", "版本更新", MessageBoxButton.OKCancel))
                    {
                        WebBrowserTask webBrowserTask = new WebBrowserTask();
                        webBrowserTask.Uri = (new Uri(updateJsonDatum.update_url));
                        webBrowserTask.Show();
                        return;
                    }
                }
                else if (updateJsonDatum.update_code == "1" && MessageBoxResult.OK == MessageBox.Show("发现新版本，您需要对版本进行升级!", "版本更新", MessageBoxButton.OK))
                {
                    WebBrowserTask webBrowserTask1 = new WebBrowserTask();
                    webBrowserTask1.Uri = (new Uri(updateJsonDatum.update_url));
                    webBrowserTask1.Show();
                    this.Exit();
                }
            });
        }

        private void Exit()
        {
            while (base.NavigationService.BackStack.Any<JournalEntry>())
            {
                base.NavigationService.RemoveBackEntry();
            }
            base.OnBackKeyPress(new CancelEventArgs());
        }

        private void HomeBookList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
        }


        private void localBookListBox_Delete1(object sender, RoutedEventArgs e)
        {
            BookList_M dataContext = (sender as MenuItem).DataContext as BookList_M;
            this.localBookListBox_DeleteDownload(dataContext);
            this.localBookSource_Delete(dataContext);
            App.LocalBook.DeleteBookList1(dataContext);
        }

        private void localBookListBox_Delete2(object sender, RoutedEventArgs e)
        {
            BookList_M dataContext = (sender as MenuItem).DataContext as BookList_M;
            this.localBookListBox_DeleteDownload(dataContext);
            this.localBookSource_Delete(dataContext);
            App.LocalBook.DeleteBookList2(dataContext);
        }

        private void localBookListBox_DeleteDownload(BookList_M m)
        {
            if (App.DownloadList.IsDownloadList(m.str_Id_M))
            {
                if (m.int_IsDownload_M == 0)
                {
                    App.DownloadList.DeleteDownloadList(m.str_DownUrl_M, m.str_Id_M);
                    return;
                }
                if (m.int_IsDownload_M == 1)
                {
                    App.DownloadList.DeleteDownloadClient();
                }
            }
        }

        private void localBookSource_Delete(BookList_M blm)
        {
            if (App.QQReader_StorageFile.IsFile(blm.str_Id_M))
            {
                App.QQReader_StorageFile.DeleteFile(blm.str_Id_M);
            }
            if (App.QQReader_StorageFile.IsFile(string.Concat(blm.str_Id_M, "chapterList")))
            {
                App.QQReader_StorageFile.DeleteFile(string.Concat(blm.str_Id_M, "chapterList"));
            }
            if (SettingHelper.IsSettings(blm.str_Id_M))
            {
                SettingHelper.DeleteSettings(blm.str_Id_M);
            }
            if (SettingHelper.IsSettings(string.Concat(blm.str_Id_M, "markerList")))
            {
                SettingHelper.DeleteSettings(string.Concat(blm.str_Id_M, "markerList"));
            }
            if (SettingHelper.IsSettings(string.Concat(blm.str_Id_M, "CurrentReaderBook")))
            {
                SettingHelper.DeleteSettings(string.Concat(blm.str_Id_M, "CurrentReaderBook"));
            }
            SaveReaderHistory.Delete(blm);
            GetNowTime.DeleteIsostore(blm.str_Cover_M);
            this.SetReaderHistory();
            ShellTile shellTile = ShellTile.ActiveTiles.FirstOrDefault<ShellTile>((ShellTile x) => x.NavigationUri.ToString().Contains(blm.str_Id_M));
            if (shellTile != null)
            {
                shellTile.Delete();
            }
        }

        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!SettingHelper.IsSettings("QQReaderHelp"))
            {
                SettingHelper.SaveInToSettings("QQReaderHelp", true);
                this.hc.SetPhoneApplicationPage(this, "MainPage");
                this.LayoutRoot.Children.Add(this.hc);
            }
            else if (this.mainPanorama.SelectedIndex == 0)
            {
                base.ApplicationBar.IsVisible = true;
            }
            if (this.mainPanorama.SelectedIndex == 0)
            {
                this.bookListBox1.ItemsSource = App.LocalBook.T_LocalBookList_VM1();
                this.bookListBox2.ItemsSource = App.LocalBook.T_LocalBookList_VM2();
            }
            foreach (BookList_M bookListM in App.LocalBook.T_LocalBookList_VM1())
            {
                if (bookListM.str_Id_M != App.ReaderFileName)
                {
                    continue;
                }
                SaveReaderHistory.Delete(bookListM);
                SaveReaderHistory.Save(bookListM);
            }
            foreach (BookList_M bookListM1 in App.LocalBook.T_LocalBookList_VM2())
            {
                if (bookListM1.str_Id_M != App.ReaderFileName)
                {
                    continue;
                }
                SaveReaderHistory.Delete(bookListM1);
                SaveReaderHistory.Save(bookListM1);
            }
            this.SetReaderHistory();
            if (!this.downloadUpdateTimeBegin)
            {
                this.downloadUpdateTime.Tick += ((object s, EventArgs ex) =>
                {
                    if (NetworkInterface.GetIsNetworkAvailable())
                    {
                        App.DownloadList.BeginDownload();
                        App.DownloadList.DownloadImage();
                    }
                });
                this.downloadUpdateTime.Start();
                this.downloadUpdateTime.Interval = TimeSpan.FromMilliseconds(1200);
                this.downloadUpdateTimeBegin = true;
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    this.CheckUpdate();
                }
                else
                {
                    Prompt.PromptMessage("提示：当前无可用网络！");
                }
            }
            App.QQReader_prePageId = App.QQReader_pageId;
            App.QQReader_pageId = "QQReader_MainPage";
            if (NetworkInterface.GetIsNetworkAvailable())
            {
                this.TodayRecommended();
            }
        }

        private void mainPanorama_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            base.Focus();
            if (base.ApplicationBar != null)
            {
                if (this.mainPanorama.SelectedIndex != 0)
                {
                    base.ApplicationBar.IsVisible = false;
                    return;
                }
                base.ApplicationBar.IsVisible = true;
            }
        }

        private void MenuItem_Loaded1(object sender, RoutedEventArgs e)
        {
            this.menuChanged = true;
        }

        private void MenuItem_Loaded2(object sender, RoutedEventArgs e)
        {
            this.menuChanged = true;
        }

        private void MenuItem_Unloaded1(object sender, RoutedEventArgs e)
        {
            this.menuChanged = false;
        }

        private void MenuItem_Unloaded2(object sender, RoutedEventArgs e)
        {
            this.menuChanged = false;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            this.RemoveHelp();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void PhoneApplicationPageBackKeyPress(object sender, CancelEventArgs e)
        {
            try
            {
                if (this.menuChanged)
                {
                    this.menuChanged = false;
                }
                else if (MessageBoxResult.Cancel != MessageBox.Show("确定要退出吗？", string.Empty, MessageBoxButton.OKCancel))
                {
                    this.downloadUpdateTime.Stop();
                    App.DownloadList.RemoveTemporaryProgress();
                    this.Exit();
                }
                else
                {
                    e.Cancel = true;
                    return;
                }
            }
            catch (Exception exception)
            {
                e.Cancel = true;
            }
        }



        private void ReaderHistory1_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (SettingHelper.IsSettings("ReaderHistory1"))
            {
                BookList_M bookListM = new BookList_M();
                bookListM = SettingHelper.GetValueFromSettings("ReaderHistory1") as BookList_M;
                NaviService.Navigate(QQReaderPage.EBookReaderPage, string.Concat("?FileName=", bookListM.str_Id_M));
                SaveReaderHistory.Delete(bookListM);
                SaveReaderHistory.Save(bookListM);
                SettingHelper.SaveInToSettings("ReaderPageBack", true);
            }
        }

        private void ListBoxItem_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (SettingHelper.IsSettings("ReaderHistory2"))
            {
                BookList_M bookListM = new BookList_M();
                bookListM = SettingHelper.GetValueFromSettings("ReaderHistory2") as BookList_M;
                NaviService.Navigate(QQReaderPage.EBookReaderPage, string.Concat("?FileName=", bookListM.str_Id_M));
                SaveReaderHistory.Delete(bookListM);
                SaveReaderHistory.Save(bookListM);
                SettingHelper.SaveInToSettings("ReaderPageBack", true);
            }
        }

        private void ListBoxItem_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (SettingHelper.IsSettings("ReaderHistory3"))
            {
                BookList_M bookListM = new BookList_M();
                bookListM = SettingHelper.GetValueFromSettings("ReaderHistory3") as BookList_M;
                NaviService.Navigate(QQReaderPage.EBookReaderPage, string.Concat("?FileName=", bookListM.str_Id_M));
                SaveReaderHistory.Delete(bookListM);
                SaveReaderHistory.Save(bookListM);
                SettingHelper.SaveInToSettings("ReaderPageBack", true);
            }
        }

        private void ListBoxItem_Tap_2(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (this.Today_ErrorImage.Visibility != Visibility.Visible && this.TodayRecommended_M.str_Id_M != "")
            {
                SettingHelper.SaveInToSettings("BookDetail", this.TodayRecommended_M);
                NaviService.Navigate(QQReaderPage.EBookDetailPage, "");
            }
        }

        private void RecommendPage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NaviService.Navigate(QQReaderPage.EBookRecommendPage, "");
        }

        private void RankPage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NaviService.Navigate(QQReaderPage.EBookRankPage, "");
        }

        private void SearchPage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NaviService.Navigate(QQReaderPage.EBookSearchPage, "");
        }

        private void TypePage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NaviService.Navigate(QQReaderPage.EBookTypePage, "");
        }

        public void RemoveHelp()
        {
            if (this.LayoutRoot.Children.IndexOf(this.hc) >= 0)
            {
                this.LayoutRoot.Children.Remove(this.hc);
            }
        }



        private void SetReaderHistory()
        {
            if (!SettingHelper.IsSettings("ReaderHistory1"))
            {
                this.ReaderHistory1_CoverNULL.Visibility = Visibility.Visible;
                this.ReaderHistory1_Cover.Visibility = Visibility.Collapsed;
                this.ReaderHistory1_Title.Text = "暂无记录";
                this.ReaderHistory1_Author.Text = "";
                this.ReaderHistory1_Progress.Text = "";
            }
            else
            {
                BookList_M bookListM = new BookList_M();
                bookListM = SettingHelper.GetValueFromSettings("ReaderHistory1") as BookList_M;
                this.ReaderHistory1_Cover.Visibility = Visibility.Visible;
                this.ReaderHistory1_CoverNULL.Visibility = Visibility.Collapsed;
                this.ReaderHistory1_Cover.Source = new BitmapImage(new Uri(bookListM.str_Cover_M, (InternalBook.IsInternalBook(bookListM.str_Id_M) ? UriKind.Relative : UriKind.RelativeOrAbsolute)));
                this.ReaderHistory1_Title.Text = bookListM.str_Title_M;
                this.ReaderHistory1_Author.Text = bookListM.str_Author_M;
                if (SettingHelper.IsSettings(string.Concat(bookListM.str_Id_M, "CurrentReaderBook")))
                {
                    LocalBookProgressList_M valueFromSettings = SettingHelper.GetValueFromSettings(string.Concat(bookListM.str_Id_M, "CurrentReaderBook")) as LocalBookProgressList_M;
                    this.ReaderHistory1_Progress.Text = GetNowTime.SetPercentageText(valueFromSettings.double_ReaderProgress_M);
                }
                if (!SettingHelper.IsSettings("ReaderHistory2"))
                {
                    this.ReaderHistory2_CoverNULL.Visibility = Visibility.Visible;
                    this.ReaderHistory2_Cover.Visibility = Visibility.Collapsed;
                    this.ReaderHistory2_Grid.Visibility = Visibility.Collapsed;
                    this.ReaderHistory2_Title.Text = "";
                    this.ReaderHistory2_Progress.Text = "";
                    return;
                }
                BookList_M bookListM1 = new BookList_M();
                this.ReaderHistory2_Cover.Visibility = Visibility.Visible;
                this.ReaderHistory2_Grid.Visibility = Visibility.Visible;
                this.ReaderHistory2_CoverNULL.Visibility = Visibility.Collapsed;
                bookListM1 = SettingHelper.GetValueFromSettings("ReaderHistory2") as BookList_M;
                this.ReaderHistory2_Cover.Source = new BitmapImage(new Uri(bookListM1.str_Cover_M, (InternalBook.IsInternalBook(bookListM1.str_Id_M) ? UriKind.Relative : UriKind.RelativeOrAbsolute)));
                this.ReaderHistory2_Title.Text = bookListM1.str_Title_M;
                if (SettingHelper.IsSettings(string.Concat(bookListM1.str_Id_M, "CurrentReaderBook")))
                {
                    LocalBookProgressList_M localBookProgressListM = SettingHelper.GetValueFromSettings(string.Concat(bookListM1.str_Id_M, "CurrentReaderBook")) as LocalBookProgressList_M;
                    this.ReaderHistory2_Progress.Text = GetNowTime.SetPercentageText(localBookProgressListM.double_ReaderProgress_M);
                }
                if (!SettingHelper.IsSettings("ReaderHistory3"))
                {
                    this.ReaderHistory3_CoverNULL.Visibility = Visibility.Visible;
                    this.ReaderHistory3_Cover.Visibility = Visibility.Collapsed;
                    this.ReaderHistory3_Grid.Visibility = Visibility.Collapsed;
                    this.ReaderHistory3_Title.Text = "";
                    this.ReaderHistory3_Progress.Text = "";
                    return;
                }
                BookList_M valueFromSettings1 = new BookList_M();
                this.ReaderHistory3_Cover.Visibility = Visibility.Visible;
                this.ReaderHistory3_Grid.Visibility = Visibility.Visible;
                this.ReaderHistory3_CoverNULL.Visibility = Visibility.Collapsed;
                valueFromSettings1 = SettingHelper.GetValueFromSettings("ReaderHistory3") as BookList_M;
                this.ReaderHistory3_Cover.Source = new BitmapImage(new Uri(valueFromSettings1.str_Cover_M, (InternalBook.IsInternalBook(valueFromSettings1.str_Id_M) ? UriKind.Relative : UriKind.RelativeOrAbsolute)));
                this.ReaderHistory3_Title.Text = valueFromSettings1.str_Title_M;
                if (SettingHelper.IsSettings(string.Concat(valueFromSettings1.str_Id_M, "CurrentReaderBook")))
                {
                    LocalBookProgressList_M localBookProgressListM1 = SettingHelper.GetValueFromSettings(string.Concat(valueFromSettings1.str_Id_M, "CurrentReaderBook")) as LocalBookProgressList_M;
                    this.ReaderHistory3_Progress.Text = GetNowTime.SetPercentageText(localBookProgressListM1.double_ReaderProgress_M);
                    return;
                }
            }
        }

        private void SetTodayRecommended(JsonData jd)
        {
            foreach (BookListJsonData bookListJsonDatum in jd.@value.record)
            {
                this.TodayRecommended_M.str_Author_M = string.Concat("作者：", bookListJsonDatum.author);
                this.TodayRecommended_M.str_Category_M = bookListJsonDatum.category;
                this.TodayRecommended_M.str_CategoryName_M = string.Concat("分类：", bookListJsonDatum.categoryName);
                this.TodayRecommended_M.str_Cover_M = bookListJsonDatum.cover;
                this.TodayRecommended_M.str_DownUrl_M = bookListJsonDatum.downUrl;
                this.TodayRecommended_M.str_Finished_M = bookListJsonDatum.finished;
                this.TodayRecommended_M.str_Free_M = bookListJsonDatum.free;
                this.TodayRecommended_M.str_HotValue_M = bookListJsonDatum.hotValue;
                this.TodayRecommended_M.str_Size_M = string.Concat("大小：", bookListJsonDatum.size, "KB");
                this.TodayRecommended_M.str_Id_M = bookListJsonDatum.id;
                this.TodayRecommended_M.str_Intro_M = bookListJsonDatum.intro;
                this.TodayRecommended_M.str_Title_M = bookListJsonDatum.title;
                this.TodayRecommended_M.str_TotalWords_M = bookListJsonDatum.totalWords;
                this.TodayRecommended_M.str_Type_M = bookListJsonDatum.type;
                this.TodayRecommended_M.str_Copyright_M = bookListJsonDatum.copyright;
            }
            this.Today_ErrorImage.Visibility = Visibility.Collapsed;
            this.Today_Title.Text = this.TodayRecommended_M.str_Title_M;
            this.Today_Intro.Text = string.Concat("\u3000\u3000", this.TodayRecommended_M.str_Intro_M.Replace("\r\n", " "));
        }

        private void TodayRecommended()
        {
            if (this.Today_ErrorImage.Visibility == Visibility.Visible)
            {
                Dictionary<string, string> strs = new Dictionary<string, string>()
                {
                    { "fromWho", "4" }
                };
                HttpPostClient httpPostClient = new HttpPostClient(strs, GetHttpInfo.GetHttpHeaders());
                httpPostClient.DownloadStringAsync(new Uri("http://appassist.3g.qq.com/book/index", UriKind.Absolute));
                httpPostClient.DownloadStringCompleted += new HttpPostClient.DownloadStringCompletedHandler(this.todayRecommended_DownloadStringCompleted);
            }
        }

        private void todayRecommended_DownloadStringCompleted(object sender, WCYCReader.Main.Core.DownloadStringCompletedEventArgs e)
        {
            base.Dispatcher.BeginInvoke(() =>
            {
                if (e.Result == null)
                {
                    return;
                }
                JsonData jsonDatum = new JsonData();
                jsonDatum = ParseJson.Parse<JsonData>(e.Result);
                this.SetTodayRecommended(jsonDatum);
            });
        }














    }
}